﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Web.Script.Serialization;

namespace web.bussines
{
    public static class my_extensions
    {
        // sort lai element cua IQueryable
        public static IQueryable<T> CustomSort<T, TPropertyType>(this IQueryable<T> collection, string propertyName, string sortOrder)
        {
            IQueryable<T> sortedlist = null;

            ParameterExpression pe = Expression.Parameter(typeof(T), "p");
            Expression<Func<T, TPropertyType>> expr = Expression.Lambda<Func<T, TPropertyType>>(Expression.Property(pe, propertyName), pe);

            if (!string.IsNullOrEmpty(sortOrder) && sortOrder == "desc")
                sortedlist = collection.OrderByDescending<T, TPropertyType>(expr.Compile()).AsQueryable();
            else
                sortedlist = collection.OrderBy<T, TPropertyType>(expr.Compile()).AsQueryable();

            return sortedlist;
        }
        // convert obj to JSON
        public static string ToJSON(this object o)
        {
            return new JavaScriptSerializer().Serialize(o);
        }

        public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

    }
}
